#include "rtconfig.h"
#include "rtthread.h"
#include <rtdevice.h>
#include "finsh.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

static rt_base_t led1_pin = -1;
static rt_base_t led2_pin = -1;

static rt_base_t key1_pin = -1;
static rt_base_t key2_pin = -1;
static rt_base_t key3_pin = -1;

static uint8_t key1_pressed = 0;
static uint8_t key2_pressed = 0;
static uint8_t key3_pressed = 0;

int led_init(void)
{
    /* set LED1 pin mode to output */
    led1_pin = rt_pin_get("PB.5");
    led2_pin = rt_pin_get("PI.8");
    if (led1_pin >= 0 && led2_pin >= 0)  
    {
        rt_pin_mode(led1_pin, PIN_MODE_OUTPUT);
        rt_pin_mode(led2_pin, PIN_MODE_OUTPUT);
        return 0;
    }
    else
    {
        return -1;
    }    
}

static void key_callback(void *args)
{
    uint8_t *flag = (uint8_t*)args;
    *flag = 1;
}

int key_init(void)
{
    key1_pin = rt_pin_get("PA.0");
    key2_pin = rt_pin_get("PH.4");
    key3_pin = rt_pin_get("PG.3");

    if(key1_pin < 0 || key2_pin < 0 || key3_pin < 0)
    {
        return -1;
    }

    rt_pin_mode(key1_pin, PIN_MODE_INPUT_PULLDOWN);
    rt_pin_attach_irq(key1_pin, PIN_IRQ_MODE_RISING, key_callback, &key1_pressed);
    rt_pin_irq_enable(key1_pin, PIN_IRQ_ENABLE);

    rt_pin_mode(key2_pin, PIN_MODE_INPUT_PULLUP);
    rt_pin_attach_irq(key2_pin, PIN_IRQ_MODE_FALLING, key_callback, &key2_pressed);
    rt_pin_irq_enable(key2_pin, PIN_IRQ_ENABLE);

    rt_pin_mode(key3_pin, PIN_MODE_INPUT_PULLUP);
    rt_pin_attach_irq(key3_pin, PIN_IRQ_MODE_FALLING, key_callback, &key3_pressed);
    rt_pin_irq_enable(key3_pin, PIN_IRQ_ENABLE);

    return 0;
}

void check_key_pressed(void)
{
    if(key1_pressed != 0)
    {
        key1_pressed = 0;
        printf("key1 pressed!\r\n");
    }

    if(key2_pressed != 0)
    {
        key2_pressed = 0;
        printf("key2 pressed!\r\n");
    }

    if(key3_pressed != 0)
    {
        key3_pressed = 0;
        printf("key3 pressed!\r\n");
    }
}

void led_flicker(void)
{
    if (led1_pin >= 0 && led2_pin >= 0) 
    {
        rt_pin_write(led1_pin, PIN_HIGH);
        rt_pin_write(led2_pin, PIN_LOW);
        rt_thread_mdelay(500);
        rt_pin_write(led1_pin, PIN_LOW);
        rt_pin_write(led2_pin, PIN_HIGH);
        rt_thread_mdelay(500);
    }
    else
    {
        printf("Invalid led pin!!!\r\n");
        rt_thread_mdelay(1000);
    }
}
